from inspect import trace
import random
import threading
from flask import Blueprint,request
import time
import datetime
from config import fieldName, makeNewSession, INTERVAL, calc_space, UPLOADDIR,debug
import config
import models
from sqlalchemy import  and_, or_, func
import traceback
import json
from API.messageAPI import send_message_to, sendMaster, upload_group_file
import os
from random import randint

timer = Blueprint('timer',__name__)


# 获取timer数据指定分页
@timer.route("/getTimerTable")
def getTimerTable():

    curPage = request.args.get("page",1,type=int)
    per_page = request.args.get("limit",15,type=int)
    func_type = request.args.get("func_type", None)
    getData = json.loads(request.args.get("searchParams","{}"))
    print(getData, bool(getData),"text",getData)
    session = makeNewSession()

    cond = []
    if func_type:
        cond.append(models.Timer.func_type==func_type)
    if getData:
        cond.append(models.Timer.title.contains(getData.get("title",'')))
        cond.append(models.Timer.beizhu.contains(getData.get("beizhu",'')))
            
    condition = and_(*cond)

    # 分页
    all_ = session.query(models.Timer).offset((curPage-1)*per_page).limit(per_page)   if not getData else session.query(models.Timer).filter(condition).offset((curPage-1)*per_page).limit(per_page)  

    # count  = session.query(func.count(all_)).scalar()
    # 获取总条数
    count =session.query(func.count(models.Timer.timerID)).scalar() if not getData else session.query(func.count(models.Timer.timerID)).filter(condition).scalar()


    result = {
        "code": 0,
        "msg": "",
        "count": count,
        "data": []
        }
    for each in all_:
        each = each.to_json()
        result['data'].append(each)
    # print(each)
    result = json.dumps(result, ensure_ascii=False, indent='\t')
    session.close()
    return result


# 删除timer数据
@timer.route("/delTimerData",methods=["POST"])
def delTimerData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    session = makeNewSession()
    try:
        session.query(models.Timer).filter(models.Timer.timerID==getData['timerID']).delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500


# 删除timer数据 多条
@timer.route("/delTimersData",methods=["POST"])
def delTimersData():
    getDatas = request.get_json()
    print("getDatas",getDatas)
    session = makeNewSession()
    try:
        session.query(models.Timer).filter(models.Timer.timerID.in_(getDatas)).delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500


# 更新timer数据
@timer.route("/updateTimerData",methods=["POST"])
def updateTimerData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    print(getData)
    session = makeNewSession()
    
    try:
        dt = datetime.datetime.now()
        t_date = dt.strftime("%Y-%m-%d")
        if getData["week"][dt.weekday()]=="1" or t_date==getData["date"]:
            cmp_time = datetime.datetime.strptime(f"{t_date} {getData['time']}",  '%Y-%m-%d %H:%M:%S').timestamp()
        else: 
            cmp_time = 0
        getData["cmp_time"]=cmp_time
        session.query(models.Timer).filter(models.Timer.timerID==getData["timerID"]).update(getData)
        session.commit()
        session.close()
        config.TIMER_NO_CHANGE = False
        return "update successfully"
    except:
        traceback.print_exc()
        session.rollback()
        session.close()
        return "update failure",500

